package com.zzy.socket.nio_selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioSelectorClient {
	public static void main(String[] args) throws IOException {
		try {
			SocketChannel socketChannel = SocketChannel.open();
			socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));

			ByteBuffer writeBuffer = ByteBuffer.allocate(80);
			ByteBuffer readBuffer = ByteBuffer.allocate(80);

			writeBuffer.put("hello(来自客户端)".getBytes());
			// flip()方法可以吧Buffer从写模式切换到读模式。
			writeBuffer.flip();

			while (true) {
				//写数据
				writeBuffer.rewind();
				socketChannel.write(writeBuffer);
				System.out.println("客户端:  -----------发消息-------- :[ " + new String(writeBuffer.array())+"]");
				
				//读数据
				readBuffer.clear();
				socketChannel.read(readBuffer);
				readBuffer.flip();
				System.out.println("客户端:  -----------接收消息-------- :[" + new String(readBuffer.array())+"]");
				
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}